package cn.sc.summer.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * rabbitmq配置类
 *
 * @author a-xin
 */
@Slf4j
@Configuration
public class RabbitConfig {

    @Resource
    private ConnectionFactory connectionFactory;

    @Bean
    public RabbitAdmin rabbitAdmin() {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 为 true 时，消息通过交换器无法匹配到队列时会返回给生产者，为 false 时，匹配不到会直接丢弃
        rabbitTemplate.setMandatory(true);
        // 设置消息从生产者发送至 rabbitmq broker 成功的回调 （保证信息到达 broker）
        // ack=true:消息成功发送到Exchange
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (Boolean.TRUE.equals(ack)) {
                log.debug("==> ConfirmCallback:     Confirm that the switch has arrived: {}", ack);
            } else {
                log.error("==> ConfirmCallback:     Confirm that the switch has arrived: {}, cause: {}, data: {}", ack, cause, correlationData);
            }
        });

        // 设置信息从交换机发送至 queue 返回信息的回调
        rabbitTemplate.setReturnsCallback(returned -> log.debug("==> ReturnCallback: message：{}, code：{}, data：{}, exchange：{}, routingKey：{}",
                returned.getMessage(),
                returned.getReplyCode(),
                returned.getReplyText(),
                returned.getExchange(),
                returned.getRoutingKey()));

        return rabbitTemplate;
    }

}
